package net.chasing.retrofit.bean.base;

import net.chasing.retrofit.RetrofitConstant;
import net.chasing.retrofit.util.MobileInfo;
import net.chasing.retrofit.util.RetrofitLog;
import net.chasing.retrofit.util.encode.CodeUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * POST + Multipart请求     PartMap标签使用的参数Map<String, RequestBody>
 */
public class BaseMultiPartReq {

    //请求体信息
    private Map<String, RequestBody> mRequestBodyMap;
    protected Map<String, Object> mSignMap;

    public BaseMultiPartReq() {
        mRequestBodyMap = new HashMap<>();
        mSignMap = new HashMap<>();
        put("timestamp", String.valueOf(System.currentTimeMillis()));
        put("echostr", UUID.randomUUID().toString().toLowerCase().replace("-", ""));
        put("driver_code", MobileInfo.getInstance().getDeviceInfo().get(MobileInfo.ANDROID_ID));
        put("app_version", RetrofitConstant.VERSION_NAME);
        put("platform", "android");
        put("appid", RetrofitConstant.APP_ID);
        put("channel", RetrofitConstant.CHANNEL);
    }

    protected void put(String key, Object value) {
        mSignMap.put(key, value);
        mRequestBodyMap.put(key, parseRequestBody(String.valueOf(value)));
    }

    //基础数据转换RequestBody
    private static RequestBody parseRequestBody(String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }

    // 注意：不要直接使用File形式，只有私有目录下的文件可以直接使用File形式，其它目录下的文件会报权限拒绝
    public void putFileBytes(String fileName, byte[] contentByte) {
        mRequestBodyMap.put(parseFileMapKey(fileName), parseByteRequestBody(contentByte));
    }

    public void putFileBytes(String key, String fileName, byte[] contentByte) {
        mRequestBodyMap.put(parseFileMapKey(key, fileName), parseByteRequestBody(contentByte));
    }

    public void putFileBytes(String key, String fileName, String mediaType, byte[] bytes) {
        mRequestBodyMap.put(parseFileMapKey(key, fileName), parseByteRequestBody(mediaType, bytes));
    }

    //文件字节数据转换RequestBody
    private static RequestBody parseByteRequestBody(byte[] contentByte) {
        return parseByteRequestBody("binary/octet-stream", contentByte);
    }

    private static RequestBody parseByteRequestBody(String mediaType, byte[] contentByte) {
        return RequestBody.create(MediaType.parse(mediaType), contentByte);
    }

    private String parseFileMapKey(String fileName) {
        return parseFileMapKey("file", fileName);
    }

    //文件名转换对应key
    private static String parseFileMapKey(String key, String fileName) {
        // fileName存在中文的话会导致上传失败，后端需要用到这个则需要进行decode
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException ignored) {
        }
        return key + "\"; filename=\"" + fileName;
    }

    public Map<String, RequestBody> getRequestBodyMap() {
        return mRequestBodyMap;
    }

    public void sign() {
        String[] keys = mSignMap.keySet().toArray(new String[]{});
        String[] afterOrder = CodeUtils.orderByASCII(keys);
        StringBuilder sb = new StringBuilder();
        for (String item : afterOrder) {
            sb.append(item).append("=").append(mSignMap.get(item)).append("&");
        }
        sb.append("key=7c0a5076038849a50d86fba336b074a3");
        String signature = sb.toString();
        RetrofitLog.i("retrofit request signature:" + signature);
        signature = CodeUtils.sha1(signature);
        String sign = signature;
        RetrofitLog.i("retrofit request sign:" + sign);

        put("sign", sign);
    }
}
